#include "imagesheet.hpp"

ImageSheet::ImageSheet(string filename, int row, int col, SDL_Color keycolor){
    SDL_Surface* surface = IMG_Load(filename.c_str());
    if(!surface)
        // FIXME better to throw error?
        SDL_Log("image sheet load failed");
    _width = surface->w/col;
    _height = surface->h/row;
    SDL_Rect rect = {0, 0, _width, _height};
    for(int i=0;i<row;i++){
        for(int j=0;j<col;j++){
            rect.x = j*col;
            rect.y = i*row;
            SDL_Surface* sur = SDL_CreateRGBSurface(0, _width, _height, 32, surface->format->Rmask, surface->format->Gmask, surface->format->Bmask, surface->format->Amask);
            SDL_SetColorKey(sur, true, SDL_MapRGBA(sur->format, keycolor.r, keycolor.g, keycolor.b, keycolor.a));
            SDL_BlitSurface(surface, &rect, sur, nullptr);
            SDL_Texture* tex = SDL_CreateTextureFromSurface(render, sur);
            _tex_list.push_back(tex);
            SDL_FreeSurface(sur);
        }
    }
    SDL_FreeSurface(surface);
    _col = col;
    _row = row;
}

SDL_Texture* ImageSheet::Get(int col, int row){
    return _tex_list.at(col+row*_col);
}

int ImageSheet::Col() const{
    return _col;
}

int ImageSheet::Row() const{
    return _row;
}

int ImageSheet::Width() const{
    return _width;
}

int ImageSheet::Height() const{
    return _height;
}

ImageSheet::~ImageSheet(){
    for(unsigned int i=0;i<_tex_list.size();i++)
        SDL_DestroyTexture(_tex_list.at(i));
    _tex_list.clear();
}
